//
//  ToolChooseViewController.m
//  ToolChooseViewController
//
//  Created by linziyuan on 16/5/20.
//  Copyright © 2016年 creative. All rights reserved.
//

#import "ToolChooseViewController.h"
#import "TLBubbleView.h"
#import "ConstDefine.h"

NSString * const LineChoose_thin = @"LineChoose_thin";
NSString * const LineChoose_normal = @"LineChoose_normal";
NSString * const LineChoose_bold = @"LineChoose_bold";
//
NSString * const PenChoose_thin = @"PenChoose_thin";
NSString * const PenChoose_bold = @"PenChoose_bold";

@interface ToolView : UIImageView

@property (nonatomic, assign) BOOL isSelected;
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) UIColor *showColor;
@property (nonatomic, assign) NSString *showLineType;
@property (nonatomic, assign) NSString *showPenType;
+ (instancetype)toolViewWithFrame:(CGRect)frame;
+ (NSString *)normalImgStrForType:(NSString *)type;
+ (NSString *)heightlightImgStrForType:(NSString *)type;

@end

@implementation ToolView
{
    UIView *_colorView;
}


+ (instancetype)toolViewWithFrame:(CGRect)frame {
    return [[self alloc] initWithFrame:frame];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _colorView = [[UIView alloc] initWithFrame:CGRectMake(frame.size.width*(1-0.68)/2.0, frame.size.height*(1-0.68)/2.0, frame.size.width*0.68, frame.size.height*0.68)];
        _colorView.backgroundColor = [UIColor clearColor];
        [self addSubview:_colorView];
        CGFloat cCorner = _colorView.frame.size.width/2*2/2;
        _colorView.layer.cornerRadius = cCorner;
        _colorView.layer.masksToBounds = YES;
        
        
        self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame = self.bounds;
        [self addSubview:_btn];
        [_btn addTarget:self action:@selector(_down:) forControlEvents:UIControlEventTouchDown];
        [_btn addTarget:self action:@selector(_up:) forControlEvents:UIControlEventTouchUpInside];
        [_btn addTarget:self action:@selector(_up:) forControlEvents:UIControlEventTouchUpOutside];
        [_btn addTarget:self action:@selector(_up:) forControlEvents:UIControlEventTouchCancel];
        CGFloat sCorner = frame.size.width/2*2/2;
        self.layer.cornerRadius = sCorner;
        self.layer.masksToBounds = YES;
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)setShowColor:(UIColor *)showColor {
    _showColor = showColor;
    _colorView.backgroundColor = showColor;
    _colorView.layer.borderWidth = 0.5;
    _colorView.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5].CGColor;
}

- (void)setIsSelected:(BOOL)isSelected {
    _isSelected = isSelected;
    if (isSelected) {
        _btn.enabled = NO;
        if (self.showColor) {
            self.layer.borderColor = [UIColor colorWithRed:77.0/255.0 green:128.0/255.0 blue:220.0/255.0 alpha:1].CGColor;
            self.layer.borderWidth = 1.0;
        }
        else if (self.showLineType) {
            NSString *imgstr = @"";
            imgstr = [ToolView heightlightImgStrForType:_showLineType];
            self.image = [UIImage imageNamed:imgstr];
        }
        else if (self.showPenType) {
            NSString *imgstr = @"";
            imgstr = [ToolView heightlightImgStrForType:_showPenType];
            self.image = [UIImage imageNamed:imgstr];
        }
    }else{
        _btn.enabled = YES;
        if (self.showColor) {
            self.layer.borderColor = [UIColor clearColor].CGColor;
            self.layer.borderWidth = 0;
        }
        else if (self.showLineType) {
            NSString *imgstr = @"";
            imgstr = [ToolView normalImgStrForType:_showLineType];
            self.image = [UIImage imageNamed:imgstr];
        }
        else if (self.showPenType) {
            NSString *imgstr = @"";
            imgstr = [ToolView normalImgStrForType:_showPenType];
            self.image = [UIImage imageNamed:imgstr];
        }
    }
   // NSLog(@"0-----isSelected :%ld",isSelected);
}

+ (NSString *)normalImgStrForType:(NSString *)type {
    NSString *imgstr = nil;
    if (type == LineChoose_thin) {
        imgstr = @"btn_line_a_normal.png";
    }else if (type == LineChoose_normal) {
        imgstr = @"btn_line_b_normal.png";
    }else if (type == LineChoose_bold) {
        imgstr = @"btn_line_c_normal.png";
    }else if (type == PenChoose_thin) {
        imgstr = @"btn_pen_a_normal.png";
    }else if (type == PenChoose_bold) {
        imgstr = @"btn_pen_b_normal.png";
    }
    return imgstr;
}

+ (NSString *)heightlightImgStrForType:(NSString *)type {
    NSString *imgstr = nil;
    if ([type isEqualToString:LineChoose_thin]) {
        imgstr = @"btn_line_a_pressed.png";
    }else if ([type isEqualToString:LineChoose_normal]) {
        imgstr = @"btn_line_b_pressed.png";
    }else if ([type isEqualToString:LineChoose_bold]) {
        imgstr = @"btn_line_c_pressed.png";
    }else if ([type isEqualToString:PenChoose_thin]) {
        imgstr = @"btn_pen_a_pressed.png";
    }else if ([type isEqualToString:PenChoose_bold]) {
        imgstr = @"btn_pen_b_pressed.png";
    }
    return imgstr;
}

- (void)_down:(UIButton*)btn
{
    UIView* view = self;
    [UIView animateWithDuration:0.1 animations:^{
        view.transform = CGAffineTransformMakeScale(1.05, 1.05);
    }];
}

- (void)_up:(UIButton*)btn
{
    UIView* view = self;
    [UIView animateWithDuration:0.1 delay:0.1 options:0 animations:^{
        view.transform = CGAffineTransformMakeScale(1, 1);
    } completion:nil];
}

@end



#pragma mark ToolChooseViewController
@interface ToolChooseViewController ()

@property (nonatomic, strong)TLBubbleView *bubbleView;
@property(nonatomic, copy) ToolChooseClickBlock toolClickBlock;
@property(nonatomic, copy) ToolTapEmptyBlock tapEmptyBlock;
@end

@implementation ToolChooseViewController
{
    NSMutableArray *_subToolViews;
    TLBubbleArrowDirectorType _bubbleDirector;
}
- (void)viewDidLoad {
    self.title = nil;
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEmpty)];
    [self.view addGestureRecognizer:tap];
    //
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(tapEmpty)];
    [self.view addGestureRecognizer:panGR];
    _subToolViews = [NSMutableArray array];
}


- (void)ToolChooseShow:(ToolChooseType)type fromVC:(UIViewController*)vc clickBlock:(ToolChooseClickBlock)toolClikBlock tapEmptyBlock:(ToolTapEmptyBlock)tapEmptyBlock {
    self.currentType = type;
    self.toolClickBlock = toolClikBlock;
    self.tapEmptyBlock = tapEmptyBlock;
    if (type == ToolChoose_color) {
        [self createColorChooseWithFromVC:vc];
    }
    else if (type == ToolChoose_line) {
        [self createImgChooseWithVC:vc typeArr:self.showLines];
    }
    else if (type == ToolChoose_pen) {
        [self createImgChooseWithVC:vc typeArr:self.showPens];
    }
}

- (void)createImgChooseWithVC:(UIViewController *)vc typeArr:(NSArray *)typeArr {
    if (!typeArr.count) {
        NSLog(@"数组为空");
        return;
    }
    [_subToolViews removeAllObjects];
    [vc addChildViewController:self];
    [vc.view addSubview:self.view];
    
    CGFloat ratio = [DataProcessing shareSingle].ratio_w;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        ratio /= 1.28;
    }
    CGFloat w = 38/ratio;
    CGFloat h_all = w*typeArr.count+20/ratio;
    CGFloat radius = 10/ratio;
    CGFloat arrowHeight = 6/ratio;
    CGPoint pt = self.view.center;
    TLBubbleArrowDirectorType bubbleType = TLBubbleArrowType_Top;
    if (self.followView) {
        pt = [_followView.superview convertPoint:_followView.center toView:self.view];
        
       if (pt.y > self.view.frame.size.height/2) {
            pt.y -= _followView.frame.size.height*0.66;
            bubbleType = TLBubbleArrowType_Bottom;
        }
        else {
            pt.y += _followView.frame.size.height*0.66;
        }
    }
    self.bubbleView = [TLBubbleView TLBubbleViewWithSize:CGSizeMake(w, h_all)];
    
    CGFloat itemY = 0.0;
    CGFloat itemW = w*0.9;
    CGFloat yOffset = (h_all-itemW*typeArr.count)*0.3;
    CGFloat hSpace = itemW * 0.1;
    
    
    for (NSInteger i = 0 ; i<typeArr.count; i++) {
        itemY = i*(itemW+hSpace)+yOffset;
        ToolView *tv = [ToolView toolViewWithFrame:CGRectMake((w-itemW)/2.0, itemY, itemW, itemW)];
        if (self.currentType == ToolChoose_line) {
            NSString *linetype = self.showLines[i];
            tv.showLineType = linetype;
            tv.isSelected = NO;
            if (self.lineType == tv.showLineType) {
                tv.isSelected = YES;
                self.currentLineImg = tv.image;
            }

        }else if (self.currentType == ToolChoose_pen) {
            NSString *Pentype = self.showPens[i];
            tv.showPenType = Pentype;
            tv.isSelected = NO;
            if (self.penType == tv.showPenType) {
                tv.isSelected = YES;
                self.currentPenImg = tv.image;
            }
        }
        [_bubbleView.contentView addSubview:tv];
        tv.btn.tag = i;
        [tv.btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [_subToolViews addObject:tv];
    }
    
    _bubbleView.radius = radius;
    _bubbleView.borderWidth = 2/ratio;
    _bubbleView.arrowHeight = arrowHeight;
    _bubbleView.arrowAngle = M_PI/5;
    _bubbleView.arrowDirectorType = bubbleType;
    _bubbleView.arrowLineRatio = 0.5;
    _bubbleView.backgroundColor = [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];
    _bubbleView.pt_Arrow = pt;
    _bubbleView.borderColor = [UIColor colorWithRed:77.0/255.0 green:128.0/255.0 blue:220.0/255.0 alpha:1];
    [_bubbleView displayMask];
    
    _bubbleDirector = bubbleType;
    [self.view addSubview:self.bubbleView];
    [self showBubbleView];
}


- (void)createColorChooseWithFromVC:(UIViewController *)vc {
    if (!self.ShowColors.count) {
        NSLog(@"颜色数组为空");
        return;
    }
    CGFloat ratio = 1.0;//[DataProcessing shareSingle].ratio_w;
//    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
//        ratio /= 1.28;
//    }
    CGFloat w = 135.0/ratio;
    CGFloat h_one = w/3.0;
    CGFloat radius = 12/ratio;
    CGFloat arrowHeight = 6/ratio;
    [_subToolViews removeAllObjects];
    [vc addChildViewController:self];
    [vc.view addSubview:self.view];
    CGPoint pt = self.view.center;
    
    TLBubbleArrowDirectorType bubbleType = TLBubbleArrowType_Top;
    if (self.followView) {
        pt = [_followView.superview convertPoint:_followView.center toView:self.view];
        
     if (pt.y > self.view.frame.size.height/2) {
            pt.y -= _followView.frame.size.height*0.66;
            bubbleType = TLBubbleArrowType_Bottom;
        }
        else {
           pt.y += _followView.frame.size.height*0.66;
        }
    }
    
    NSInteger lineCount = self.ShowColors.count/3;
    if (self.ShowColors.count%3 > 0) {
        lineCount+=1;
    }
    self.bubbleView = [TLBubbleView TLBubbleViewWithSize:CGSizeMake(w, h_one*lineCount)];
    
    
    CGFloat itemW = (w*0.9)/3 * 0.9;
    CGFloat xOffset = (w*0.1)/2;
    CGFloat yOffset = (h_one - itemW)/2;
    CGFloat itemHSpace = (w*0.1)/3;
    CGFloat itemX = 0.0;
    CGFloat itemY = 0.0;
    NSInteger row = 0;
    for (NSInteger i = 0;i < self.ShowColors.count; i++) {
        UIColor *color = self.ShowColors[i];
        if (i%3 == 0 && i !=0) {
            row+=1;
            itemX = 0.0;
        }
        itemX = (i%3 * (itemW+itemHSpace)) + xOffset;
        itemY = row*itemW + yOffset;
        ToolView *tv = [ToolView toolViewWithFrame:CGRectMake(itemX, itemY, itemW, itemW)];
        tv.showColor = color;
        [_bubbleView.contentView addSubview:tv];
        tv.btn.tag  = i;
        [tv.btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        
        if (self.defualtIndex == i && self.defualtIndex<(self.ShowColors.count-1)) {
            tv.isSelected = YES;
        }
        [_subToolViews addObject:tv];
    }
    _bubbleView.radius = radius;
    _bubbleView.borderWidth = 2/ratio;
    _bubbleView.arrowHeight = arrowHeight;
    _bubbleView.arrowAngle = M_PI/4;
    _bubbleView.arrowDirectorType = bubbleType;
    _bubbleView.arrowLineRatio = 0.5;
    _bubbleView.backgroundColor = [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];
    _bubbleView.pt_Arrow = pt;
    _bubbleView.borderColor = [UIColor colorWithRed:77.0/255.0 green:128.0/255.0 blue:220.0/255.0 alpha:1];
    [_bubbleView displayMask];
    
    _bubbleDirector = bubbleType;
    [self.view addSubview:self.bubbleView];
    [self showBubbleView];
}


- (void)showBubbleView {
    
    CGPoint pt = _bubbleView.center;
    if (_bubbleDirector == TLBubbleArrowType_Bottom) {
        pt.y += _bubbleView.frame.size.height*0.5;
        _bubbleView.center = pt;
        pt.y -= _bubbleView.frame.size.height*0.5;
    }else {
        pt.y -= _bubbleView.frame.size.height*0.5;
        _bubbleView.center = pt;
        pt.y += _bubbleView.frame.size.height*0.5;
    }
    _bubbleView.transform= CGAffineTransformMakeScale(0.0000001, 0.0000001);
    [UIView animateWithDuration:0.4 delay:0.0 usingSpringWithDamping:0.6 initialSpringVelocity:15 options:UIViewAnimationOptionCurveEaseIn animations:^{
        _bubbleView.center = pt;
        _bubbleView.transform = CGAffineTransformIdentity;
        self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.05];
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)click:(id)sender {
    UIButton *btn = (id)sender;
    ToolView *ctv = _subToolViews[btn.tag];
    ctv.isSelected = YES;
    for (ToolView * tv in _subToolViews) {
        if (tv!=ctv) {
            tv.isSelected = NO;
        }
    }
    if (self.currentType == ToolChoose_color) {
        self.currentColor = self.ShowColors[btn.tag];
        self.defualtIndex = btn.tag;
    }
    else if (self.currentType == ToolChoose_line) {
        self.lineType = self.showLines[btn.tag];
        self.currentLineImg = ctv.image;
    }
    else if (self.currentType == ToolChoose_pen) {
        self.penType = self.showPens[btn.tag];
        self.currentPenImg = ctv.image;
    }
    if (self.toolClickBlock) {
        self.toolClickBlock(self,btn.tag);
    }
}

- (void)close {
    [self tapEmpty];
}
- (void)tapEmpty
{
    CGPoint pt = _bubbleView.center;
    
    if (_bubbleDirector == TLBubbleArrowType_Bottom) {
        pt.y += _bubbleView.frame.size.height*0.5;
    }else {
       pt.y -= _bubbleView.frame.size.height*0.5;
    }
    [UIView animateWithDuration:0.3f animations:^{
        _bubbleView.center = pt;
        _bubbleView.transform= CGAffineTransformMakeScale(0.0000001, 0.0000001);
        self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.00];
    } completion:^(BOOL finished) {
        [_bubbleView removeFromSuperview];
        [self.view removeFromSuperview];
        [self willMoveToParentViewController:nil];
        [self removeFromParentViewController];
        if (self.tapEmptyBlock) {
            self.tapEmptyBlock(self);
        }
    }];
}

+ (NSString *)tcNormalImgForType:(NSString *)type {
    return [ToolView normalImgStrForType:type];
}
+ (NSString *)tcHeightlightImgForType:(NSString *)type {
    return [ToolView heightlightImgStrForType:type];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
